package com.footprint.quartz.callable;

import java.io.File;
import java.io.FileWriter;
import java.sql.Timestamp;

import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.DefaultHttpClient;

import com.footprint.common.httpclient.HttpGetUtil;

/**
 * @author lsj
 *
 */
public class AirChinaCallable extends BasicCallable{
	static final String TMP_URL = "http://et.airchina.com.cn/InternetBooking/AirLowFareSearchExternal.do?&tripType=OW&searchType=FARE&flexibleSearch=false&directFlightsOnly=false&fareOptions=1.FAR.X&outboundOption.originLocationCode=PEK&outboundOption.destinationLocationCode=PVG&outboundOption.departureDay=20&outboundOption.departureMonth=12&outboundOption.departureYear=2011&outboundOption.departureTime=NA&guestTypes%5B0%5D.type=ADT&guestTypes%5B0%5D.amount=1&guestTypes%5B1%5D.type=CNN&guestTypes%5B1%5D.amount=2&pos=AIRCHINA_CN&lang=zh_CN&guestTypes%5B2%5D.type=INF&guestTypes%5B2%5D.amount=0";
	
	static HttpClient httpClient = new DefaultHttpClient();
	
	public AirChinaCallable() {
	}

	@Override
	public String call() throws Exception {
		String jumpUrl = genJumpUrl(HttpGetUtil.doGet(httpClient, TMP_URL));
		System.out.println(new Timestamp(System.currentTimeMillis()) + "jumpUrl   " + jumpUrl);
		if(null == jumpUrl) {
			return "fail";
		} else {
			// System.out.println(HttpGetUtil.doGet(httpClient, jumpUrl));
			File f = new File("d:\\result.txt");
			FileWriter fw = new FileWriter(f, true);
			fw.append("\n\n\n--------------------------" + new Timestamp(System.currentTimeMillis()));
			fw.append(HttpGetUtil.doGet(httpClient, jumpUrl));
			fw.close();
			return "success";
		}
	}

	private static String genJumpUrl(String html) {
		String beginStr = "formManager.submitExternal({url: '";
		String endStr = "', failureUrl:";
		int beginIndex = html.indexOf(beginStr);
		int endIndex = html.indexOf(endStr);
		if(beginIndex >= 0 && endIndex > beginIndex) {
			String t = html.substring(beginIndex + beginStr.length(), endIndex);
			// System.out.println(t);
			return t;
		}
		return null;
	}
}
